/*******************************************************************************
 *    系统名称   : 约汗乐动力接口/后台管理系统
 *    客户             : 约汗乐动力
 *    文件名        ： StringUtils.java
 *              (C) Copyright 博智乐创 Corporation 2015
 *               All Rights Reserved.
 *              http://www.bozlc.com
 * *****************************************************************************
 *    注意： 本内容仅限于约汗乐动力软件公司内部使用，未经许可禁止转发
 ******************************************************************************/
package com.xiake.utils;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// TODO: Auto-generated Javadoc
/**
 * 常用字符工具类.
 */
public class StringUtils {

	/** The Constant SEARCH_SEPERATOR. */
	public static final String SEARCH_SEPERATOR = "[ ,;|　]";
    
    /**
     * 判断是否是空.
     *
     * @param str the str
     * @return boolean
     */
	public static boolean isEmpty(Object str) {
		return (str == null || "".equals(str));
	}
	
	/**
	 * 根据给定的正则[ ,;|　]，切割字符串.
	 *
	 * @param str the str
	 * @return string[]
	 */
	public static String[] convertStringToArray(String str) {
		return convertStringToArray(str, null, 0);
	}
	
	/**
	 * 根据给定的正则[ ,;|　]，切割字符串.
	 *
	 * @param str the str
	 * @param limit 参数控制模式应用的次数，因此影响所得数组的长度
	 * @return string[]
	 */
	public static String[] convertStringToArray(String str, int limit) {
		return convertStringToArray(str, null, limit);
	}
	
	/**
	 * 根据给定的正则参数split，切割字符串，不限制数据长度.
	 *
	 * @param str the str
	 * @param split the split
	 * @return string[]
	 */
	public static String[] convertStringToArray(String str, String split) {
		return convertStringToArray(str, split, 0);
	}
	
	/**
	 * 根据给定的正则参数split，切割字符串，限制数据长度.
	 *
	 * @param str the str
	 * @param split the split
	 * @param limit the limit
	 * @return string[]
	 */
	public static String[] convertStringToArray(String str, String split, int limit) {
		List<String> list = convertStringToList(str, split, limit);
		if (list == null) {
			return null;
		}
		return list.toArray(new String[0]);
	}

	/**
	 * Convert string to list.
	 *
	 * @param str the str
	 * @return the list
	 */
	public static List<String> convertStringToList(String str) {
		return convertStringToList(str, null, 0);
	}

	/**
	 * Convert string to list.
	 *
	 * @param str the str
	 * @param limit the limit
	 * @return the list
	 */
	public static List<String> convertStringToList(String str, int limit) {
		return convertStringToList(str, null, limit);
	}

	/**
	 * Convert string to list.
	 *
	 * @param str the str
	 * @param split the split
	 * @return the list
	 */
	public static List<String> convertStringToList(String str, String split) {
		return convertStringToList(str, split, 0);
	}

	/**
	 * Convert string to list.
	 *
	 * @param str the str
	 * @param split the split
	 * @param limit the limit
	 * @return the list
	 */
	public static List<String> convertStringToList(String str, String split, int limit) {
		if (str == null) {
			return null;
		}
		String[] ret = null;
		if (split == null) {
			split = SEARCH_SEPERATOR;
		}
		ret = str.split(split, limit);//根据匹配给定的正则表达式来拆分此字符串
		if (ret == null) {
			return null;
		}

		List<String> list = new ArrayList<String>();
		for (int i = 0; i < ret.length; i++) {
			String s = ret[i];
			if (s == null) {
				continue;
			}
			s = s.trim();
			if (!"".equals(s)) {
				list.add(s);
			}
		}
		return list;
	}

	/**
	 * To string value.
	 *
	 * @param o the o
	 * @return the string
	 */
	public static String toStringValue(Object o) {
		String tmp = toString(o);
		if (tmp == null || tmp.length() <= 2) {
			return null;
		}
		return tmp.substring(1, tmp.length() - 1);
	}

	/**
	 * To string.
	 *
	 * @param o the o
	 * @return the string
	 */
	public static String toString(Object o) {
		if (o == null) {
			return null;
		}
		if (o.getClass().isArray()) {
			String className = o.getClass().getName();
			if ("[I".equals(className)) {
				int[] a = (int[]) o;
				return Arrays.toString(a);
			} else if ("[J".equals(className)) {
				long[] a = (long[]) o;
				return Arrays.toString(a);
			} else if ("[S".equals(className)) {
				short[] a = (short[]) o;
				return Arrays.toString(a);
			} else if ("[C".equals(className)) {
				char[] a = (char[]) o;
				return Arrays.toString(a);
			} else if ("[B".equals(className)) {
				byte[] a = (byte[]) o;
				return Arrays.toString(a);
			} else if ("[F".equals(className)) {
				float[] a = (float[]) o;
				return Arrays.toString(a);
			} else if ("[D".equals(className)) {
				double[] a = (double[]) o;
				return Arrays.toString(a);
			} else if ("[Z".equals(className)) {
				boolean[] a = (boolean[]) o;
				return Arrays.toString(a);
			} else {
				Object[] a = (Object[]) o;
				return Arrays.toString(a);
			}
		} else {
			return o.toString();
		}
	}

	/**
	 * Gets the string length.
	 *
	 * @param str the str
	 * @param charSet the char set
	 * @return the string length
	 */
	public static final int getStringLength(String str, String charSet) {
		if (str == null || str.length() == 0)
			return 0;
		try {
			byte[] strBytes = null;
			if (charSet == null) {
				strBytes = str.getBytes();
			} else
				strBytes = str.getBytes(charSet);
			return strBytes.length;
		} catch (Exception e) {
			byte[] strBytes = str.getBytes();
			return strBytes.length;
		}
	}

	/**
	 * Gets the string length.
	 *
	 * @param str the str
	 * @return the string length
	 */
	public static final int getStringLength(String str) {
		return getStringLength(str, "UTF-8");
	}

	/**
	 * Load from file.
	 *
	 * @param fname the fname
	 * @return the string
	 * @throws FileNotFoundException the file not found exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static String loadFromFile(String fname) throws FileNotFoundException, IOException {
		return loadFromFile(fname, null);
	}

	/**
	 * Load from file.
	 *
	 * @param fname the fname
	 * @param encoding the encoding
	 * @return the string
	 * @throws FileNotFoundException the file not found exception
	 * @throws UnsupportedEncodingException the unsupported encoding exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static String loadFromFile(String fname, String encoding) throws FileNotFoundException, UnsupportedEncodingException, IOException {
		FileInputStream fis = null;
		InputStreamReader isr = null;
		StringBuffer ret = new StringBuffer();
		try {
			fis = new FileInputStream(fname);
			if (encoding != null) {
				isr = new InputStreamReader(fis, encoding);
			} else {
				isr = new InputStreamReader(fis);
			}

			char[] cbuffer = new char[1024];
			int read = isr.read(cbuffer);
			while (read >= 0) {
				ret.append(cbuffer, 0, read);
				read = isr.read(cbuffer);
			}

			return ret.toString();
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
			try {
				isr.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * Save to file.
	 *
	 * @param fname the fname
	 * @param str the str
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static void saveToFile(String fname, String str) throws IOException {
		if (str == null)
			return;
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(fname));
			bw.write(str);
		} finally {
			try {
				if (bw != null)
					bw.close();
			} catch (Exception e1) {
			}
		}
	}

	/**
	 * Parses the int.
	 *
	 * @param str the str
	 * @return the int
	 */
	public static int parseInt(String str) {
		return parseInt(str, -1);
	}

	/**
	 * Parses the int.
	 *
	 * @param str the str
	 * @param defaultValue the default value
	 * @return the int
	 */
	public static int parseInt(String str, int defaultValue) {
		if (str == null || "".equals(str.trim())) {
			return defaultValue;
		}
		int num = 0;
		try {
			num = Integer.parseInt(str);
		} catch (Exception e) {
			num = defaultValue;
		}
		return num;
	}

	/**
	 * Parses the long.
	 *
	 * @param str the str
	 * @return the long
	 */
	public static long parseLong(String str) {
		return parseLong(str, -1);
	}

	/**
	 * Parses the long.
	 *
	 * @param str the str
	 * @param defaultValue the default value
	 * @return the long
	 */
	public static long parseLong(String str, long defaultValue) {
		if (str == null || "".equals(str.trim())) {
			return defaultValue;
		}
		long num = 0;
		try {
			num = Long.parseLong(str);
		} catch (Exception e) {
			num = defaultValue;
		}
		return num;
	}

	/**
	 * Checks if is null string.
	 *
	 * @param str the str
	 * @return true, if is null string
	 */
	public static boolean isNullString(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * Check string.
	 *
	 * @param str the str
	 * @param defaultValue the default value
	 * @return the string
	 */
	public static String checkString(String str, String defaultValue) {
		if (str == null || "".equals(str.trim())) {
			return defaultValue;
		}
		return str;
	}

	/**
	 * Judge china.
	 *
	 * @param content the content
	 * @param maxSize the max size
	 * @return the string
	 */
	public static String judgeChina(String content, Integer maxSize) {
		Integer index = 0;

		StringBuffer sBuffer = new StringBuffer();
		for (int i = 0; i < content.length(); i++) {
			String retContent = content.substring(i, i + 1);
			// 生成一个Pattern,同时编译一个正则表达式
			boolean isChina = retContent.matches("[\u4E00-\u9FA5]");
			boolean isCapital = retContent.matches("[A-Z]");

			if (index == maxSize) {
				sBuffer.append("..");
				break;
			}

			if ((index == maxSize - 1 && isChina)) {
				continue;
			}

			if (isChina || isCapital) {
				index = index + 2;
			} else {
				index = index + 1;
			}
			sBuffer.append(retContent);

			if (index > maxSize) {
				sBuffer.append("...");
				break;
			}
		}
		return sBuffer.toString();
	}

	/**
	 * Convert asc to str.
	 *
	 * @param str the str
	 * @return the string
	 */
	public static String convertASCToStr(String str) {

		Pattern p = Pattern.compile("&#(\\d+);", Pattern.CASE_INSENSITIVE);
		Matcher matcher = p.matcher(str);

		while (matcher.find()) {
			String findStr = matcher.group(1);
			char c = (char) Integer.parseInt(findStr);
			str = str.replace("&#" + findStr + ";", String.valueOf(c));
		}
		return str;
	}

	/**
	 * 将数组以 split 分隔。组成一个字符串.
	 *
	 * @param str            数组
	 * @param split            以此分隔
	 * @return the string
	 */
	public static String convertArrayToString(String[] str, String split) {
		String result = "";
		for (String s : str) {
			if (!isEmpty(s)) {
				result += s + split;
			}
		}
		return result;
	}

	/**
	 * Convert list to string array.
	 *
	 * @param list the list
	 * @return the string[]
	 */
	public static String[] convertListToStringArray(List<String> list) {
		return list.toArray(new String[0]);
	}

	/**
	 * 将 1,2,12,14 转换为list.
	 *
	 * @param str the str
	 * @return the list
	 */
	public static List<Long> convertStringToLongList(String str) {
		List<Long> list = new ArrayList<Long>();
		if (str != null && !str.equals("")) {
			String[] sArray = str.split(",");
			for (String s : sArray) {
				if (!StringUtils.isEmpty(s)) {
					long i = safeParseLong(s);
					if (i != default_value)
						list.add(i);
				}
			}
		}
		return list;
	}

	/**
	 * 将 1,2,12,14 转换为list.
	 *
	 * @param str the str
	 * @return the list
	 */
	public static List<Integer> fromStringToIntegerList(String str) {
		List<Integer> list = new ArrayList<Integer>();
		if (str != null && !str.equals("")) {
			String[] sArray = str.split(",");
			for (String s : sArray) {
				if (!StringUtils.isEmpty(s)) {
					Integer i = safeParseInt(s);
					if (i != default_value)
						list.add(i);
				}
			}
		}
		return list;
	}

	/** The Constant default_value. */
	private static final int default_value = -219939611;

	/**
	 * Safe parse long.
	 *
	 * @param s the s
	 * @return the long
	 */
	private static long safeParseLong(String s) {
		try {
			return Long.parseLong(s);
		} catch (Exception e) {
			return default_value;
		}
	}

	/**
	 * Safe parse int.
	 *
	 * @param s the s
	 * @return the int
	 */
	private static int safeParseInt(String s) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
			return default_value;
		}
	}

	/**
	 * Array to connect.
	 *
	 * @param array the array
	 * @return the string
	 */
	public static String arrayToConnect(String[] array) {
		String result = "";
		for (String s : array) {
			result += " " + s;
		}
		return result;
	}

	/**
	 * Connenct two arrays.
	 *
	 * @param o1 the o1
	 * @param o2 the o2
	 * @return the string[]
	 */
	public static String[] connenctTwoArrays(String[] o1, String[] o2) {
		if (o2 == null || o2.length == 0) {
			return o1;
		}
		if (o1 == null || o1.length == 0) {
			return o2;
		}
		String[] o3 = new String[o1.length + o2.length];
		for (int i = 0; i < o1.length; i++) {
			o3[i] = o1[i];
		}
		int flag = 0;
		for (int j = o1.length; j < o3.length; j++) {
			o3[j] = o2[flag];
			flag++;
		}
		return o3;
	}

	/**
	 * The main method.
	 *
	 * @param args the arguments
	 */
	public static void main(String[] args) {
		/* String s = "啊上的变化@张三三 @哈师大";

		 String string = "kldslkjlfksdjfd";
		 System.out.println(judgeChina(string, 10));*/
		/* String str = "2012 MC又来了&#160;HotDog圣诞狂欢夜上海&#160;Part2";
		 System.out.println(convertASCToStr(str));
		
		 List<String> list = new ArrayList<String>();
		 list.add("123");
		 list.add("456");
		 convertListToStringArray(list);

		 String s1 = "a,b,c,d,";
		 String s2 = ",e,f,g";
		 String[] ss1 = s1.split(",");
		 String[] ss2 = s2.split(",");
		 String[] s3 = connenctTwoArrays();
		 for(String s : s3){
		 System.out.println(s);
		 }*/

	}
	
	/**
	 * Gets the length by word.
	 *
	 * @param str the str
	 * @return the length by word
	 */
	public static  int getLengthByWord(String str) {
		int result = 0;
		char[] cArray = str.toCharArray();
		for (char c : cArray) {
			int a = c;
			// 是字母
			if (a >= 65 && a <= 122) {
				result += 1;
			}else{
				result += 2;
			}
		}
		return result;
	}

	// 字母 65 - 122
//	public static void main(String[] args) {
//		new BaseService().getLengthByWord("1");
//	}

	/**
	 * Gets the length by words.
	 *
	 * @param strList the str list
	 * @return the length by words
	 */
	public static int getLengthByWords(List<String> strList) {
		int result = 0;
		for (String s : strList) {
			result += getLengthByWord(s);
		}
		return result;
	}
}
